package command

import (
	"fmt"

	"github.com/fatih/color"

	"gitee.com/csingo/cHelper"
	"gitee.com/csingo/csingo/resource/version"
)

var (
	names = []string{"console", "project", "config", "app", "view", "server", "tool", "version"}
)

type HelpCommand struct{}

func (i *HelpCommand) Desc() *CommandDesc {
	return &CommandDesc{
		Name: "help",
		Methods: []*CommandMethod{
			{
				Name: "doc",
				Desc: "查看帮助文档",
				Params: []*CommandParams{
					{Name: "name", Desc: "模块名称 [ console | project | config | app | view | server | tool | version ]", Optional: true},
				},
			},
		},
	}
}

func (i *HelpCommand) Doc(name string) {
	if !cHelper.InArray(names, name) {
		name = ""
	}

	type document struct {
		Name string
		Desc string
		Type uint8
	}
	var doc = []*document{}
	var maxlen int

	ver, _ := version.Asset("version/version")
	color.Set(color.FgHiCyan)
	fmt.Println(string(ver))
	fmt.Println("")

	for _, instance := range Instances {
		desc := instance.Desc()

		if name != "" && name != desc.Name {
			continue
		}

		doc = append(doc, &document{
			Name: desc.Name,
			Desc: "",
			Type: 0,
		})
		maxlen = max(maxlen, desc.Name)
		for _, method := range desc.Methods {
			methodLabel := fmt.Sprintf("  %s::%s", desc.Name, method.Name)
			doc = append(doc, &document{
				Name: methodLabel,
				Desc: method.Desc,
				Type: 1,
			})
			maxlen = max(maxlen, methodLabel)
			for _, param := range method.Params {
				var paramLabel string
				if param.Optional {
					paramLabel = fmt.Sprintf("      [--%s]", param.Name)
				} else {
					paramLabel = fmt.Sprintf("      --%s", param.Name)
				}
				doc = append(doc, &document{
					Name: paramLabel,
					Desc: fmt.Sprintf("    %s", param.Desc),
					Type: 2,
				})
				maxlen = max(maxlen, paramLabel)
			}
		}
		doc = append(doc, &document{
			Name: "",
			Desc: "",
			Type: 1,
		})
	}

	//color.Set(color.FgGreen)
	//fmt.Printf("%s\n\n%s\n\n%s\n\n", "========================================", "eg: csingo command [--option=] ...", "========================================")
	for _, item := range doc {
		maxlenStr := fmt.Sprintf("%d", maxlen*-1)
		switch item.Type {
		case 0:
			color.Set(color.FgHiMagenta)
		case 1:
			color.Set(color.FgGreen)
		case 2:
			color.Set(color.FgHiBlue)
		}
		fmt.Printf("%"+maxlenStr+"s %s\n", item.Name, item.Desc)
	}
	color.Set(color.FgWhite)
}
